package com.example;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程池
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2025/6/28 17:04
 * @updateUser:     MI
 * @updateTime:     2025/6/28 17:04
 * @updateRemark:   修改内容
 * @version:        1.0
 */
public class ThreadCountdownLatchExample {


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        CountDownLatch countDownLatch = new CountDownLatch(1);
        System.out.println("主线程开始执行，提交子任务...");
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                // 开始执行任务
                try {
                    System.out.println("子线程任务开始执行...");
                    // 模拟任务执行时间
                    Thread.sleep(3000);
                    System.out.println("子线程任务执行完成，准备调用 countDown()");
                    // 任务执行结束后，计数器减 1
                    countDownLatch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("主线程阻塞等待子任务完成...");
        // 阻塞main线程，当任务执行结束调用countDown() 方法 使得计数器归零后，唤醒main线程
        countDownLatch.await();
        executorService.shutdown();
        System.out.println("子任务已完成，主线程继续执行");
    }
}
